'''
Created on Nov 27, 2012

@author: Himanshu
'''
import os
from featureset import gesture
import cPickle as pickle
import generators
import numpy as np

#    """test = LOOCV()
#    test.setFeatureSet(featureList)
#    test.setTargetVector(scoreList)
#    computedClass = test.experiment(classifier)
#    print computedClass
#    print test.countErrors(computedClass)"""
    

def correctNorms(gestSet):
    for key in gestSet.keys():
        noInstances = gestSet[key].returnaX().__len__()
        aN = []
        netaN = []
        worldaN = []
        for i in range(noInstances):
            aN_old = gestSet[key].returnaNorm()[i]
            netaN_old = gestSet[key].netaNorm[i]
            worldaN_old = gestSet[key].returnworldaNorm()[i]
            l = aN_old.__len__()
            aN_temp = [0]*l
            netaN_temp = [0]*l
            worldaN_temp = [0]*l 
            for j in range(l):
                aN_temp[j] = aN_old[j]
                netaN_temp[j] = netaN_old[j]
                worldaN_temp[j] = worldaN_old[j]
            aN.append(aN_temp)
            netaN.append(netaN_temp)
            worldaN.append(worldaN_temp)
        gestSet[key].aNorm = aN
        gestSet[key].netaNorm = netaN
        gestSet[key].worldaNorm = worldaN
            
            
def gaussSmooth(array , smoothSize , sigma):
    """ smooth the window means using a gaussian function. End cases are handled by reflection. SmoothSize
    has to be an odd int!!!"""
    if ((smoothSize == 0) or (sigma == 0)):
        return array
    else:
        end = array.__len__()
        padding = smoothSize/2
        frontPad = array[0:padding]
        frontPad.reverse()
        backPad = array[end - padding : end]
        backPad.reverse()
        array = frontPad + array + backPad
        gaussFilter = getFilter(smoothSize,sigma)
        smoothArray = []
        for i in range(padding , end + padding):        
            localWindowMean = np.dot(gaussFilter,array[i-padding:i+padding + 1])
            smoothArray.append(localWindowMean)
        return smoothArray
#                
                
def getFilter(size,sigma):
    """
    return an array with a gaussian function of size and variance sigma
    """
    mean = (size-1)/2
    gaussFilter = [0]*size
    for i in range(0,size):
        gaussFilter[i] = np.exp(-1.*(i-mean)*(i-mean)/(2*sigma*sigma))
    gaussFilter /= np.trapz(gaussFilter)
    return gaussFilter


def combineGestures(gest1 , gest2):
    if (gest1.getGestureName() == gest2.getGestureName()):
        naNorm = gest1.returnaNorm() + gest2.returnaNorm()
        naX = gest1.returnaX() + gest2.returnaX()
        naY = gest1.returnaY() + gest2.returnaY()
        naZ = gest1.returnaZ() + gest2.returnaZ()
        ngX = gest1.returngX() + gest2.returngX()
        ngY = gest1.returngY() + gest2.returngY()
        ngZ = gest1.returngZ() + gest2.returngZ()
        ntimes = gest1.returnTimes() + gest2.returnTimes()
        nfeature = (naNorm , naX , naY , naZ , ngX , ngY , ngZ , ntimes)
        return gesture(gest1.getGestureName() , nfeature)
    else:
        print "Cannot combine gestures of different names! " + gest1.getGestureName() + " " + gest2.getGestureName()
        return None

def readAllPickles():
    """
    return type - dictionary
    argument - none
    """
    path = os.getcwd() + '\pickles'
    gestureSet = {}
    for fileName in os.listdir(path):
        if (os.path.splitext(fileName)[1] == ".pkl"):
            pklFile = open(path + '\\' + fileName, 'rb')
            gestureNameFull = pickle.load(pklFile)
            noGestures = pickle.load(pklFile)
            gest = pickle.load(pklFile)
            if gest.getGestureName() in gestureSet:
                oldGesture = gestureSet[gest.getGestureName()]
                del gestureSet[gest.getGestureName()]
                ngest = combineGestures(gest , oldGesture)
                gestureSet[ngest.getGestureName()] = ngest
            else:
                gestureSet[gest.getGestureName()] = gest
            pklFile.close()
    return gestureSet



def modGests(gestureSet  , startAccels):
    for gestName in gestureSet.keys():
        gest = gestureSet.pop(gestName)
        ngest = gesture(gestName , (gest.returnaNorm() , gest.returnaX() , gest.returnaY() , gest.returnaZ() , 
                                    gest.returngX() , gest.returngY() , gest.returngZ() , gest.returnTimes()))
        ngest.setStartAccel(startAccels[gestName])
        generators.removeGrav(ngest)
        generators.calcWorldA(ngest)
        pickleName = gest.getGestureName() + '_mod_grav.pkl'
        output = open(os.getcwd()+'\pickles\\'+pickleName, 'wb')
        pickle.dump(gestName , output)
        pickle.dump(gest.returnaNorm().__len__() , output)
        pickle.dump(ngest , output)
        print 'Pickle modified, name = ', pickleName
        gestureSet[gestName] = ngest
        
def modGestsPosVelEner(gestureSet):
    for gestName in gestureSet.keys():
        print "Running Gesture " , gestName
        gest = gestureSet.pop(gestName)
        ngest = gesture(gestName , (gest.returnaNorm() , gest.returnaX() , gest.returnaY() , gest.returnaZ() , 
                                    gest.returngX() , gest.returngY() , gest.returngZ() , gest.returnTimes()))
        ngest.setStartAccel(gest.getStartAccel())
        ngest.netaX = gest.netaX
        ngest.netaY = gest.netaY
        ngest.netaZ = gest.netaZ
        ngest.netaNorm = gest.netaNorm
        ngest.worldaX = gest.worldaX
        ngest.worldaY = gest.worldaY
        ngest.worldaZ = gest.worldaZ
        ngest.worldaNorm = gest.worldaNorm
        ngest.setVelocities(generators.getGestVel(gest))
        ngest.setPositions(generators.getGestPos(ngest))
        ngest.setEnergy(generators.getGestEnergy(ngest))
        pickleName = gest.getGestureName() + '_mod_Pos_Vel.pkl'
        output = open(os.getcwd()+'\pickles-test\\'+pickleName, 'wb')
        pickle.dump(gestName , output)
        pickle.dump(gest.returnaNorm().__len__() , output)
        pickle.dump(ngest , output)
        print 'Pickle modified, name = ', pickleName
        gestureSet[gestName] = ngest
        
#def getStartPoints():
#    path = os.getcwd() + '\pickles'
#    for fileName in os.listdir(path):
#        if (os.path.splitext(fileName)[1] == ".pkl"):
#            pklFile = open(path + '\\' + fileName, 'rb')
#            gestureNameFull = pickle.load(pklFile)
#            print gestureNameFull
#            noGestures = pickle.load(pklFile)
#            gest = pickle.load(pklFile)
#            for inst in gest.returnTimes():
#                print inst[0]
        
        
#    gestName = 'Swing_Phone2'
#    start = 5590
#    end = 5594
#    g = 4
#    
#    path = os.getcwd() + '\pickles'
#    pklFile  = open(path + '\\' + gestName + '.pkl' , 'rb')
#    gestureNameFull = pickle.load(pklFile)
#    noGestures = pickle.load(pklFile)
#    gest = pickle.load(pklFile)
#    rownum = 0
#    ax=[]
#    ay=[]
#    az=[]
#    gx=[]
#    gy=[]
#    gz=[]
#    time=[]
#    pklFile.close()
#
#    
#    with open(os.getcwd()+"/phidgetData//" + gestName + '.csv', 'r') as csvfile:
#        reader = csv.reader(csvfile, dialect = 'excel')
#        for row in reader:
#            rownum += 1
#            if (rownum>=end):
#                break
#            if (rownum>=start):
#                time.append(float(row[0])*1000 + float(row[1])/1000)
#                ax.append(float(row[2]))
#                ay.append(float(row[3]))
#                az.append(float(row[4]))
#                gx.append(float(row[5]))
#                gy.append(float(row[6]))
#                gz.append(float(row[7]))
#        
#    print gest.aX[g].__len__()
#    print gest.aY[g].__len__()
#    print gest.aZ[g].__len__()
#    print gest.gX[g].__len__()
#    print gest.gY[g].__len__()
#    print gest.gZ[g].__len__()
#    print gest.times[g].__len__()
#    print gest.aNorm[g].__len__()
#    gest.aX[g] = ax + gest.aX[g]
#    gest.aY[g] = ay + gest.aY[g]
#    gest.aZ[g] = az + gest.aZ[g]
#    gest.gX[g] = gx + gest.gX[g]
#    gest.gY[g] = gy + gest.gY[g]
#    gest.gZ[g] = gz + gest.gZ[g]
#    gest.times[g] = time + gest.times[g]
#    rawFeatures = [gest.aX[g] , gest.aY[g] , gest.aZ[g]]
#    aRaw = np.sum(np.abs(np.transpose(rawFeatures))**2,axis = -1)**(1./2)
#    gest.aNorm[g] = aRaw
#
#    print gest.aX[g].__len__()
#    print gest.aY[g].__len__()
#    print gest.aZ[g].__len__()
#    print gest.gX[g].__len__()
#    print gest.gY[g].__len__()
#    print gest.gZ[g].__len__()
#    print gest.times[g].__len__()
#    print gest.aNorm[g].__len__()
#    print gest.getGestureName()
#    pickleName = gestName + '_mod.pkl'
#    output = open(os.getcwd()+'\pickles\\'+pickleName, 'wb')
#    pickle.dump(gestName , output)
#    pickle.dump(gest.returnaNorm().__len__() , output)
#    pickle.dump(gest , output)
#    output.close()
        
    